package com.wctj.api.base.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
* Base64工具类
* @author lzg
*/
@Slf4j
public class Base64Util {

    private static final Logger log = LoggerFactory.getLogger(Base64Util.class);

    /**
    * 根据url获取资源的base64字符串
    * @author qy
    * @since 2023/1/11 16:53
    * @param sourceUrl: 资源url
    * @return base64字符串
    **/
    public static String file(String sourceUrl) {
        String encode = null;
        try {
            URL url = new URL(sourceUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream inputStream = conn.getInputStream();
            encode = cn.hutool.core.codec.Base64.encode(inputStream);
        } catch (Exception e) {
            log.error("获取资源base64加密字符串异常", e);
        }
        return encode;
    }


    public static String md5HexBase64(String base64Encoded) {
        // 对Base64编码的字符串进行解码
        byte[] decodedBytes = Base64.decodeBase64(base64Encoded);

        // 将解码后的字节数组转换为字符串
        String decodedPassword = new String(decodedBytes, Charset.forName("UTF-8"));

        // 生成MD5哈希值并转换为16进制字符串
        String md5Hex = DigestUtils.md5Hex(decodedPassword);
        return md5Hex;
    }


    public static String md5Hex(String md5Hex) {
        // 生成MD5哈希值并转换为16进制字符串
        return DigestUtils.md5Hex(md5Hex);
    }


    public static void main(String[] args) {
//        log.info(Base64Util.file("https://imlf.8531.cn/webpic/W0202301/W020230111/W020230111378333016351.jpg"));
        // 189cc5f221a72a5a773496a078091246
        String pwd = "a123456";
        log.info("md5Hex1:{}", md5Hex(pwd));
        log.info("md5Hex2:{}",  MD5Utils.md5(pwd));
        log.info("md5Hex3:{}",  MD5Utils.encodeMD5Hex(pwd));

        log.info("aaa:{}",getPayload("eyJhbGciOiJFUzI1NiJ9.eyJzYyI6IlRNWSIsInN1YiI6Im5iZ0A4NTMxLmNvbSIsInVpZCI6NDE5LCJnaWQiOjEzODcsImlpZCI6Ijk0Mjg0Iiwicm4iOiLlpKfmtIvmtYvor5UiLCJleHAiOjE2NjQxODQwMjgsImlhdCI6MTY2NDE4MDQyOCwidGlkIjoxMDIsInV0IjoyfQ.SPBSozBXwYJclw55Y3OS19tDqUC6_-uZbWD8VQUnzVROCStuvts-m3Cp7sh9Y8ShwxwcsekBKY3qY25OhbYOmA"));
        String msg = "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInN5c3RlbUNvZGUiOiJsZXR1dSIsInVzZXJUeXBlIjoyLCJleHAiOjE3Mjk1OTg1MDAsInVzZXJJZCI6MSwiaWF0IjoxNzI5NTg3NzAwLCJ1c2VybmFtZSI6ImFkbWluIn0.0QtYK2mPjpRkQupxNYHgxggWIHdmHCYAokFyT-5ieCJgssgnn-JF0es1ao0Lv_qXTm5qsGdpnq_BQNqGeIwlzQ";

        log.info("getPayload:{}", getPayload(msg));
    }


    private static Map<String, String> getPayload(String auth) {
        String sub = auth.split("\\.")[1];
        return JsonUtils.readFromBytes(java.util.Base64.getUrlDecoder().decode(sub),Map.class);
    }

}